from lib.cuckoo.common.abstracts import Signature
import re


class FileBehavior(Signature):
    name = "file_behavior"
    description = "file behavior"
    severity = 3
    categories = ["reg"]
    authors = ["none"]
    minimum = "2.0"

    # 这里一定要写要监控的API名称，否则会监控所有的API
    # 这里过滤的api名称，直接影响到on_call函数中的call["arguments"]["regkey"]
    # 因为不是所有api都有这个regkey参数，如果不写过滤可能会在on_call报错
    filter_apinames = [
        "FILE_write",
        "FILE_modified",
        "FILE_truncate",
        "FILE_read",
    ]

    def on_call(self, call, process):
        if call["api"] in ["NtOpenFile", "NtCreateFile"] and call["status"]:
            if "1.txt" in call["arguments"]["filepath"]:
                self.mark_call()
        elif call["api"] == "NtWriteFile" and call["status"]:
            self.mark_call()

    def on_call(self, call, process):
        regkey = call["arguments"]["regkey"]
        regvalue = call["arguments"]["value"]

        # 当上面的API被调用的时候，使用正则过滤注册表键，使用self.mark打印出来
        if re.match(self.indicator, regkey, re.IGNORECASE):
            self.mark(process=process['process_name'], reg_key=regkey, reg_value=regvalue)

    # 如果在on_call函数中有调用mark函数，这里就返回has_marks()
    def on_complete(self):
        return self.has_marks()
